package me.zhengjie.modules.supplier_app.service;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderPersonService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderPersonDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * Created by bruce on 19/10/7.
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtSupplierUserDetailsService implements UserDetailsService {

    @Autowired
    private TServiceproviderPersonService tServiceproviderPersonService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TServiceproviderPersonDTO personDTO = tServiceproviderPersonService.findByUsername(s);
        if(personDTO==null) {
            personDTO = tServiceproviderPersonService.findByPhone(s);
        }
        if(personDTO == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return createJwtUser(personDTO);
        }
    }

     public UserDetails createJwtUser(TServiceproviderPersonDTO personDTO) {
         return new JwtUser(
                 personDTO.getId(),
                 personDTO.getAccount(),
                 personDTO.getPersonPassword(),
                 null, //user.getAvatar(),
                 null, //user.getEmail(),
                 personDTO.getPhone(), //user.getPhone(),
                 null, //Optional.ofNullable(user.getDept()).map(DeptSmallDTO::getName).orElse(null),
                 null, //Optional.ofNullable(user.getJob()).map(JobSmallDTO::getName).orElse(null),
                 new ArrayList<GrantedAuthority>(), //permissionService.mapToGrantedAuthorities(user),
                 personDTO.getIsDelete() == 0,
                 null, //user.getCreateTime(),
                 null, //user.getLastPasswordResetTime(),
                 0L,  //isAdmin,是否管理员,工程师角色不用
                 personDTO.getPersonName(),
                 personDTO.getServiceproviderId(),
                 personDTO.getServiceproviderName()
         );
     }
}
